import uvicorn
import socket
import webbrowser
from fastapi import FastAPI
import base64
import ddddocr
from io import BytesIO
from PIL import Image
from fastapi.responses import HTMLResponse
from pydantic import BaseModel,Field
from typing import Union


description = """
_________________
### 项目说明：

* <strong>会HttpPost协议即可调用的原则！</strong>

* 支持部署 <strong>本地</strong> 和 <strong>服务器</strong> .

* <strong>长期更新 免费开源 欢迎赞助 </strong>

### 关于作者：

* 哔哩哔哩 <https://space.bilibili.com/37887820>

* GitHub <https://github.com/81NewArk/StupidOCR>
 
### 项目依赖：DDDDOCR+FastApi
_________________
"""

app = FastAPI(
    title='StupidOCR',
    description=description,
    version="1.0.7",
     )





class Model_Common_VerificationCode(BaseModel):
    ImageBase64: str

@app.post("/api.Common_VerificationCode", tags=["通用验证码识别"],summary='文字验证码',description='上传图片Base64编码')
async def Common_VerificationCode(item: Model_Common_VerificationCode):
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    ocr = ddddocr.DdddOcr(show_ad=False)
    res = ocr.classification(base64.b64decode(item.ImageBase64))
    return {"result":res,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}







class Model_Arithmetic_VerificationCode(BaseModel):
    ImageBase64: str

@app.post("/api.Arithmetic_VerificationCode", tags=["通用验证码识别"],summary='算术验证码',description='上传图片Base64编码')
async def Common_VerificationCode(item: Model_Arithmetic_VerificationCode):
    ocr = ddddocr.DdddOcr(show_ad=False)
    res = ocr.classification(base64.b64decode(item.ImageBase64))
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    print(res)
    if "+" or '-' or 'x' or '/' or "÷" or "*" not in res:
        result= "error"
    if '+' in res:
        result = int(res.split('+')[0]) + int(res.split('+')[1][:-1])
    if '-' in res:
        result = int(res.split('-')[0]) - int(res.split('-')[1][:-1])
    if 'x' in res:
        result = int(res.split('x')[0]) * int(res.split('x')[1][:-1])
    if 'X' in res:
        result = int(res.split('X')[0]) * int(res.split('X')[1][:-1])
    if '÷' in res:
        result = int(res.split('÷')[0]) / int(res.split('÷')[1][:-1])
    if '*' in res:
        result = int(res.split('*')[0]) * int(res.split('*')[1][:-1])

    return {"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}







class Model_Move_Slider(BaseModel):
    MovePicture: str
    Background: str

@app.post("/api.Slider_Move",summary='缺口为滑动的单独图片，返回坐标', description='识别模式1：缺口图片为单独图片', tags=['滑块验证码识别'])
async def Common_VerificationCode(item: Model_Move_Slider):
    ocr = ddddocr.DdddOcr(show_ad=False)
    result = ocr.slide_match(base64.b64decode(item.MovePicture), base64.b64decode(item.Background),simple_target=True)
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)

    return{"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}







class Model_Comparison_Slider(BaseModel):
    HaveGap_ImageBase64: str
    Full_ImageBase64: str

@app.post("/api.Slider_Comparison", summary='缺口原图和完整原图对比识别，无单独滑动的缺口图片，返回坐标', description='识别模型2：一张为有缺口原图，一张为完整原图',tags=['滑块验证码识别'])
async def Comparison_Slider(item: Model_Comparison_Slider):
    ocr = ddddocr.DdddOcr(det=False, ocr=False)
    result = ocr.slide_comparison(base64.b64decode(item.HaveGap_ImageBase64), base64.b64decode(item.Full_ImageBase64))

    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)

    return{"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}







class Model_Text_Choose_Click(BaseModel):
    ChoiceClick_ImageBase64: str

@app.post("/api.Text_Choose_Click", summary='文字选点验证码识别，返回坐标', description='选点识别返回坐标', tags=['选点类验证码识别'])
async def Text_Choose_Click(item: Model_Text_Choose_Click):
    ocr1 = ddddocr.DdddOcr(show_ad=False)
    ocr2 = ddddocr.DdddOcr(det=True, show_ad=False)
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)

    res = ocr2.detection(base64.b64decode(item.ChoiceClick_ImageBase64))
    img = Image.open(BytesIO(base64.b64decode(item.ChoiceClick_ImageBase64)))
    res = ocr2.detection(base64.b64decode(item.ChoiceClick_ImageBase64))
    result = {}
    for box in res:
        x1, y1, x2, y2 = box
        result[ocr1.classification(img.crop(box))] = [ x1+(x2-x1)//2，y1+(y2-y1)//2]  # 文字位置
    return{"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}









class Model_ICO_Choose_Click(BaseModel):
    ICO_ChooseClick_ImageBase64: str
    Background_ImageBase64: str

@app.post("/api.Icon_Choose_Click", summary='图标点选验证码，返回坐标', description='点选识别返回坐标', tags=['选点类验证码识别'])
async def ICO_Choose_Click(item: Model_ICO_Choose_Click):
    ocr = ddddocr.DdddOcr(show_ad=False)
    result = ocr.slide_match(base64.b64decode(item.ICO_ChooseClick_ImageBase64), base64.b64decode(item.Background_ImageBase64),simple_target=True)
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    return {"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}








class Model_Target_Detection(BaseModel):
    ImageBase6: str

@app.post("/api.Target_Detection", summary='扩展功能f，可用返回的坐标截取图片', description='检查图片内的文字 图标，返回坐标', tags=['扩展功能，目标侦察'])
async def Target_Detection(item:Model_Target_Detection):
    ocr = ddddocr.DdddOcr(det=True)
    result = ocr.detection(base64.b64decode(item.ImageBase64))
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    return {"result":result,"BiliBili":"https://space.bilibili.com/37887820","supports":"http://"+ip+":6688/support"}





@app.get("/support", response_class=HTMLResponse,tags=['赞助StupidOCR'],summary='打开网页：http://localhost:6688/support',include_in_schema=False)
async def support():
    return """
<html>
   <head>
    <title>赞助作者</title>
   </head>
    <body>
    <h1 align="center">给无业的作者打赏</h1>
    <h3 align="center">微信&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;支付宝</h3>
    <h1 align="center"> <img  src="" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    <img  src="" ></h1>
    <hr>
    <h2 align="left"> GitHub： <a href="https://github.com/81NewArk/StupidOCR">https://github.com/81NewArk/StupidOCR</a></h2>
    <h2 align="left"> BiLiBiLi： <a href="https://space.bilibili.com/37887820">https://space.bilibili.com/37887820</a></h2>
    <h2 align="left"> E-Mail  ： 751247667@qq.com</h2>
    </body>
</html>
         """

if __name__ == '__main__':
    print('''

   _____   _                     _       _    ____     _____   _____  
  / ____| | |                   (_)     | |  / __ \   / ____| |  __ \ 
 | (___   | |_   _   _   _ __    _    __| | | |  | | | |      | |__) |
  \___ \  | __| | | | | | '_ \  | |  / _` | | |  | | | |      |  _  / 
  ____) | | |_  | |_| | | |_) | | | | (_| | | |__| | | |____  | | \ \ 
 |_____/   \__|  \__,_| | .__/  |_|  \__,_|  \____/   \_____| |_|  \_/
                        | |                                           
                        |_|                                           

                开发文档：http://localhost:6688/docs
                赞助页面：http://127.0.0.1:6688/support

                代码编写：81NewArk
 
    ''')
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    webbrowser.open("http://"+ip+":6688/support")
    webbrowser.open("http://localhost:6688/docs")
    uvicorn.run(app, port=6688, host="0.0.0.0")

